package com.sduept.nwld.mobile.rest;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.inject.Inject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.bigdata.document.entity.core.RecordAttachment;
import com.sduept.bigdata.document.services.RecordAttachmentManager;
import com.sduept.bigdata.web.core.manager.BannerManager;
import com.sduept.bigdata.web.core.model.BannerInfo;
import com.sduept.nwld.dataserver.manager.document.DocumentDirManager;
import com.sduept.nwld.dataserver.manager.document.DocumentDirManager.DirDto;
import com.sduept.nwld.dataserver.manager.document.HtmlDocumentManager;
import com.sduept.nwld.dataserver.model.AppDocument;
import com.sduept.nwld.dataserver.model.AppDocumentDir;
import com.sduept.nwld.dataserver.model.HtmlDocument;
import com.sduept.nwld.mobile.manager.MobileUtil;
import com.sduept.utils.Base64;
import com.sduept.utils.DateUtil;
import com.sduept.utils.ZipUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 客户端文件类操作rest
 * 
 * @author zht
 *
 */
@Slf4j
@RestController
@RequestMapping("/mobileFileService/")
public class MobileFileService {
	@Autowired
	private DocumentDirManager docManager;
	@Autowired
	private BannerManager bm;
	@Autowired
	private HtmlDocumentManager hdm;
	@Autowired
	private CommonDocumentProperties pros;
	@Inject
	private MobileUtil mobileUtil;//SQL注入检测类
  
	@Autowired
	private RecordAttachmentManager ra;
	/**
	 * 下载附件
	 * 
	 * @return
	 * */

	@GetMapping("/downLoadFile/{fileId}")
	public String downLoadFile(@PathVariable("fileId") String fileId) {
		try {
			fileId =mobileUtil.SQLInjectCheck(fileId);
		} catch (Exception e) {
			e.printStackTrace();
			return "查找文件失败，无法下载";
		}
		String res = null;
		if (!"null".equals(fileId)) {
			AppDocument rd = docManager.findAppDocumentById(fileId);
			if (rd != null) {// id在数据库中有
				// 需要优化
				String filePath = pros.getDocumentPath() + rd.getPath();
				try {
					res = Base64.encodeFromFile(filePath);
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				res = "查找文件失败，无法下载";
			}
		}
		return res;
	}
	
	/**
	 * 压缩并下载附件
	 * 
	 * @return
	 * */

	@GetMapping("/downloadFileZip/{fileId}")
	public String downloadFileZip(@PathVariable("fileId") String fileId) {
		try {
			fileId = mobileUtil.SQLInjectCheck(fileId);
		} catch (Exception e) {
			e.printStackTrace();
			return "查找文件失败，无法下载";
		}
		String res = null;
		if (!"null".equals(fileId)) {
			AppDocument rd = docManager.findAppDocumentById(fileId);
			if (rd != null) {// id在数据库中有
				// 需要优化
				String filePath = pros.getDocumentPath() + rd.getPath();
				List<File> fileList = new ArrayList<File>();
				File docFile = new File(filePath);
				fileList.add(docFile);
				String tmpZipPath = pros.getDocumentPath() + rd.getId() + ".zip";
				ZipUtil.zipFile(tmpZipPath, fileList);
				try {
					res = Base64.encodeFromFile(tmpZipPath);
			    	ZipUtil.deletefile(tmpZipPath);//删除zip
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				res = "查找文件失败，无法下载";
			}
		}
		return res;
	}
	
	
	/**从RecordAttachment中下载附件
	 * @param fileId
	 * @return
	 */
	@GetMapping("/downLoadAttachment/{attachmentId}")
	public String downLoadAttachment(@PathVariable("attachmentId") String attachmentId) {
		try {
			attachmentId =mobileUtil.SQLInjectCheck(attachmentId);
		} catch (Exception e) {
			log.info(attachmentId+"sql关键字检测未通过！");
			return "";
		}
		String res = null;
		if (!"null".equals(attachmentId)) {
			RecordAttachment rd = ra.getAttachmentById(attachmentId);
			if (rd != null) {// id在数据库中有
				// 需要优化
				String filePath = pros.getDocumentPath() + rd.getPath();
				try {
					res = Base64.encodeFromFile(filePath);
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				log.info(attachmentId+"附件不存在！");
				res = "";
			}
		}
		return res;
	}
	
	
	
	/**
	 * 获取轮播图片列表,不带内容
	 * 
	 * @return
	 * */

	@GetMapping("/getScrollPicture")
	public String getScrollPicture() {
		List<BannerInfo> banners = bm.getBanners();
		for(BannerInfo b:banners) {
			b.setLink(""); 
		}
		return JSONArray.toJSONString(banners);
	}
	/**
	 * 获取有效期内的轮播图片列表,不带内容
	 * 
	 * @return
	 * */

	@GetMapping("/getValidScrollPicture")
	public String getValidScrollPicture() {
		List<BannerInfo> banners = bm.getValidBanners();
		for(BannerInfo b:banners) {
			b.setLink(""); 
		}
		return com.alibaba.fastjson.JSONArray.toJSONString(banners);
	}

	/**
	 * 下载轮播图片
	 * 
	 * @return
	 * */

	@GetMapping("/downLoadScrollPicture/{picId}")
	public String downLoadScrollPicture(@PathVariable("picId") String picId) {
		try {
			picId = mobileUtil.SQLInjectCheck(picId);
		} catch (Exception e) {
			e.printStackTrace();
			return "查找文件失败，无法下载";
		}
		String res = null;
		BannerInfo pic = bm.getBannerById(picId);
		if (pic != null) {// id在数据库中有
			// 需要优化
			String filePath = pros.getImagePath() + pic.getPath();
			try {
				res = Base64.encodeFromFile(filePath);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			res = "查找文件失败，无法下载";
		}
		return res;
	}

	/**
	 * 根据路径下载图片
	 * 
	 * @return
	 * */

	@GetMapping("/downLoadPicByPath/{iconPath}")
	public String downLoadPicByPath(@PathVariable("iconPath") String iconPath) {
		try {
			iconPath =mobileUtil.SQLInjectCheck(iconPath);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		String res = null;
		// 需要优化
		String filePath = pros.getImagePath() + iconPath;
		try {
			res = Base64.encodeFromFile(filePath);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return res;
	}

	/**
	 * 根据目录id和日期获取文档(分为按年查询和按月查询两种情况)
	 * 
	 * @return
	 * */

	@GetMapping("/getDocumentsByDirIdAndDate/{dirId}/{date}")
	public String getDocumentsByDirIdAndDate(@PathVariable("dirId") String pid,@PathVariable("date") String date) {
		try {
			pid = mobileUtil.SQLInjectCheck(pid);
			date = mobileUtil.SQLInjectCheck(date);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		List<AppDocument> rtn=new ArrayList<AppDocument>();
		if(date.indexOf("-")==-1){
			//按年查询
			rtn=docManager.findDocumentsByPidAndDate(pid,null,Integer.parseInt(date));
		}else{
			//按月查询
			Calendar calendar=Calendar.getInstance();
			calendar.setTime(DateUtil.getDateByString(date+"-01", DateUtil.pattern_ymd));
			int year=calendar.get(Calendar.YEAR);
			int month=calendar.get(Calendar.MONTH)+1;
			rtn=docManager.findDocumentsByPidAndDate(pid,month,year);
		}
		return JSONArray.toJSONString(rtn);
	}
	/**
	 * 根据目录id获取文档
	 * 
	 * @return
	 * */

	@GetMapping("/getDocumentsByDirId/{dirId}")
	public String getDocumentsByDirId(@PathVariable("dirId") String pid) {
		try {
			pid = mobileUtil.SQLInjectCheck(pid);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		List<AppDocument> rtn=docManager.getDocsByPid(pid);
		return JSONArray.toJSONString(rtn);
	}
	/**
	 * 根据目录id获取目录或文档
	 * 
	 * @return
	 * */

	@GetMapping("/getDirsAndDocsByDirId/{dirId}")
	public String getDirsAndDocsByDirId(@PathVariable("dirId") String pid) {
		try {
			pid = mobileUtil.SQLInjectCheck(pid);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		return getDirsAndDocsByPid(pid);
	}
	/**
	 * 根据目录name获取目录或文档
	 * 
	 * @return
	 * */

	@GetMapping("/getDirsAndDocsByDirName/{dirName}")
	public String getDirsAndDocsByDirName(@PathVariable("dirName") String dirName) {
		try {
			dirName = mobileUtil.SQLInjectCheck(dirName);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		AppDocumentDir dir=docManager.findDocumentDirByName(dirName);
		if(null!=dir){
			return  getDirsAndDocsByPid(dir.getId());
		}
		return "";
	}
	private String getDirsAndDocsByPid(String pid){
		JSONObject jso=new JSONObject();
		List<AppDocumentDir> dirs=docManager.findAppDocumentDirByPid(pid);
		List<AppDocument> docs=docManager.getDocsByPid(pid);
		jso.put("dir", dirs);
		jso.put("doc", docs);
		return jso.toString();
	}
	
	/**
	 * 根据目录name获取所有的子目以及每个目录下的文档
	 * 
	 * @return
	 * */

	@GetMapping("/getAllDirsAndDocsByDirName/{dirName}")
	public String getAllDirsAndDocsByDirName(@PathVariable("dirName") String dirName) {
		try {
			dirName = mobileUtil.SQLInjectCheck(dirName);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		AppDocumentDir dir=docManager.findAppDocumentDirByName(dirName);
		DirDto dto=docManager.getAllDirsAndDocsByDir(dir);
		return JSONObject.toJSONString(dto);
	}
	
	/**
	 * 根据目录ID获取所有的子目以及每个目录下的文档
	 * 
	 * @return
	 * */

	@GetMapping("/getAllDirsAndDocsByDirId/{dirId}")
	public String getAllDirsAndDocsByDirId(@PathVariable("dirId") String dirId) {
		try {
			dirId = mobileUtil.SQLInjectCheck(dirId);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		AppDocumentDir dir=docManager.findAppDocumentDirById(dirId);
		DirDto dto=docManager.getAllDirsAndDocsByDir(dir);
		return JSONObject.toJSONString(dto);
	}
	
	/**
	 * 根据title获取内容
	 * 
	 * @return
	 * */

	@GetMapping("/getHtmlContentByTitle/{title}")
	public String getHtmlContentByTitle(@PathVariable("title") String title) {
		try {
			title = mobileUtil.SQLInjectCheck(title);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		List<HtmlDocument> rtn=hdm.findHtmlDocumentsByTitle(title);
		if(rtn.size()>0){
			return rtn.get(0).getDescription();
		}
		return "";
	}
	/**
	 * 轮播图根据id获取内容
	 * 
	 * @return
	 * */

	@GetMapping("/getHtmlContentById/{id}")
	public String getHtmlContentById(@PathVariable("id") String id) {
		try {
			id = mobileUtil.SQLInjectCheck(id);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		BannerInfo rtn=bm.getBannerById(id);
		if(null!=rtn){
			return rtn.getLink();
		}
		return "";
	}

	
}
